
/**
 * HttpExceptions
 *
 * @author glory.xu
 */

import HttpExceptions from '../exceptions/http_exceptions';

export default () => {
  return async function errorHandler(ctx, next) {
    try {
      await next();
    } catch (err) {
      ctx.app.emit('error', err, ctx);

      let status = err.status || 500;
      const error: any = {};

      if (err instanceof HttpExceptions) {
        status = err.httpCode;
        error.requestUrl = `${ctx.method} : ${ctx.path}`;
        error.msg = err.msg;
        error.code = err.code;
        error.httpCode = err.httpCode;
      } else {
        error.code = 500;
        error.errsInfo =
          status === 500 && ctx.app.config.env === 'prod'
            ? 'Internal Server Error'
            : err.message;
      }
      ctx.body = error;
      if (status === 422) {
        ctx.body.detail = err.errors;
      }
      ctx.status = status;
    }
  };
};
